'use strict';

const db = uniCloud.database();
const userCollection = db.collection('users');
const jwt = require('jsonwebtoken');
const SECRET_KEY = 'b354257d7b0b076dd751f535a8ae86cc'; // 实际应用中应该使用环境变量存储

exports.main = async (event, context) => {
	const { action, params } = event;
	// 路由分发
	switch (action) {
		case 'login':
			return await login(params);
		default:
			return {
				code: 404,
				message: '未找到对应的方法'
			};
	}
};

// 微信登录
async function login(params) {
	try {
		const { code, userInfo } = params;
		
		if (!code) {
			return {
				code: 1,
				message: '缺少微信登录code'
			};
		}
		
		// 调用微信接口获取openid
		const wxResult = await uniCloud.httpclient.request(
			`https://api.weixin.qq.com/sns/jscode2session?appid=${process.env.WX_APPID}&secret=${process.env.WX_SECRET}&js_code=${code}&grant_type=authorization_code`,
			{
				dataType: 'json'
			}
		);
		
		if (wxResult.status !== 200 || wxResult.data.errcode) {
			return {
				code: 2,
				message: '微信登录失败: ' + (wxResult.data.errmsg || '未知错误')
			};
		}
		
		const { openid, session_key } = wxResult.data;
		
		// 查找或创建用户
		let user = await userCollection.where({ openid }).get();
		
		if (user.data.length === 0) {
			// 新用户，创建记录
			const newUser = {
				openid,
				nickname: userInfo.nickName,
				avatar: userInfo.avatarUrl,
				gender: userInfo.gender,
				country: userInfo.country,
				province: userInfo.province,
				city: userInfo.city,
				create_time: Date.now(),
				update_time: Date.now()
			};
			
			const insertResult = await userCollection.add(newUser);
			user = {
				_id: insertResult.id,
				...newUser
			};
		} else {
			// 更新用户信息
			user = user.data[0];
			await userCollection.doc(user._id).update({
				nickname: userInfo.nickName,
				avatar: userInfo.avatarUrl,
				gender: userInfo.gender,
				country: userInfo.country,
				province: userInfo.province,
				city: userInfo.city,
				update_time: Date.now()
			});
		}
		
		// 生成token
		const token = jwt.sign(
			{
				uid: user._id,
				openid
			},
			SECRET_KEY,
			{ expiresIn: '30d' }
		);
		
		return {
			code: 0,
			message: '登录成功',
			token,
			userInfo: {
				uid: user._id,
				nickname: userInfo.nickName,
				avatar: userInfo.avatarUrl
			}
		};
	} catch (error) {
		console.error('登录失败', error);
		return {
			code: 500,
			message: '服务器错误: ' + error.message
		};
	}
}